// 蛇类
class Sanke{
  // 蛇头元素
  head:HTMLElement
  // 蛇的身体
  bodies:HTMLCollection
  // 容器
  element:HTMLElement
  constructor(){
    this.element = document.getElementById('sanke')
    this.head = document.querySelector('#sanke > div')
    this.bodies = this.element.getElementsByTagName('div')
  }

  get X(){
    return this.head.offsetLeft
  }
  get Y(){
    return this.head.offsetTop
  }
  setXY(flag:string,value:number){
    let bd = this.bodies[1] as HTMLElement
    let off = this.leftTop(flag)
    if(value === this[flag]) return
    if(value < 0 || value > 290){
      this.error()
    }
    if(bd&&bd[off] === value){
      value = this[flag] < value ? this[flag] - 10 : this[flag] + 10
    }
    // 移动身体
    this.moveBody()
    if(flag === 'X'){
      this.head.style.left = value + 'px'
    }else{
      this.head.style.top = value + 'px'
    }
    this.checkHeadBody()
  }
  leftTop(flag){
    return flag === 'X' ? 'offsetLeft' : 'offsetTop'
  }
  // set X(value:number){
  //   if(this.X === value) return
  //   if(value < 0 || value > 290){
  //     this.error()
  //   }
  //   if(this.bodies[1]&&(this.bodies[1] as HTMLElement).offsetLeft === value){
  //     value = this.X < value ? this.X - 10 : this.X + 10
  //   }
  //   // 移动身体
  //   this.moveBody()
  //   this.head.style.left = value + 'px'
  //   this.checkHeadBody()
  // }
  // set Y(value:number){
  //   if(this.Y === value) return
  //   if(value < 0 || value > 290){
  //     this.error()
  //   }
  //   if(this.bodies[1]&&(this.bodies[1] as HTMLElement).offsetTop === value){
  //     value = this.Y < value ? this.Y - 10 : this.Y + 10
  //   }
  //   // 移动身体
  //   this.moveBody()
  //   this.head.style.top = value + 'px'
  //   this.checkHeadBody()
  // }
  // 增加身体长度
  addBody(){
    this.element.insertAdjacentHTML('beforeend','<div></div>')
  }
  // 身体移动
  moveBody(){
    for(let i = this.bodies.length - 1; i > 0; i--){
      let x = (this.bodies[i - 1] as HTMLElement).offsetLeft;
      let y = (this.bodies[i - 1] as HTMLElement).offsetTop;
      (this.bodies[i] as HTMLElement).style.left = x + 'px';
      (this.bodies[i] as HTMLElement).style.top = y + 'px';

    }
  }
  // 清空身体
  clearBody(){
    for(let i = 1; i < this.bodies.length; i++){
      this.element.removeChild(this.bodies[i])
    }
    this.head.style.left = 0 + 'px';
    this.head.style.top = 0 + 'px'
  }
  // 蛇头是否与身体重叠
  checkHeadBody(){
    for(let i = 1; i < this.bodies.length; i++){
      let bd = (this.bodies[i] as HTMLElement)
      if(this.X === bd.offsetLeft && this.Y === bd.offsetTop){
        this.error()
      }
    }
  }
  error(){
    throw new Error("挑战失败！！继续加油鸭");
    
  }
}
export default Sanke
